<template>
	<a-card :bordered="false">
		<div class="table-page-search-wrapper">
			<a-form layout="inline">
				<a-row :gutter="48">

					<a-col :md="8" :sm="24">
						<a-form-item label="BOM名称">
							<a-input allowClear v-model="queryParam.bomName" placeholder="请输入BOM名称" />
						</a-form-item>
					</a-col>

					<a-col :md="8" :sm="24">
						<a-form-item label="分类">
							<a-select allowClear v-model="queryParam.bomClass" placeholder="请选择BOM分类">
								<a-select-option :value="item.id" v-for="(item, index) in typeList" :key="index">
									{{ item.value }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :md="8" :sm="24">
						<a-form-item label="料号">
							<a-input allowClear v-model="queryParam.materialCode" placeholder="请输入料号" />
						</a-form-item>
					</a-col>
					<a-col :md="6" :sm="24">
						<a-form-item label="状态">
							<a-radio-group button-style="solid" v-model="queryParam.isDisable">
								<a-radio-button :value="null">
									全部
								</a-radio-button>
								<a-radio-button v-for="item in [{ label: '正常', value: 1 }, { label: '停用', value: 2 }]" :key="item.value"
									:value="item.value">
									{{
										item.label
									}}
								</a-radio-button>
							</a-radio-group>
						</a-form-item>
					</a-col>

					<a-col :md="!advanced && 8 || 24" :sm="24">
						<span class="table-page-search-submitButtons"
							:style="advanced && { float: 'right', overflow: 'hidden' } || {}">
							<a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
							<a-button style="margin-left: 8px"
								@click="() => { queryParam = { isDisable: null }; $refs.table.refresh(true) }">重置</a-button>
						</span>
					</a-col>

				</a-row>
			</a-form>
		</div>


		<div class="table-operator">
			<!--      <a-button type="primary" @click="">物料查询</a-button>-->
			<a-button type="primary" @click="bomToPool" v-if="hasBtnPremission(['emsMaterialPool:addList'])"
				:loading="toPoolLoading">录入采购池</a-button>
			<a-button type="primary" v-if="hasBtnPremission(['emsBom:add'])" @click="$refs.addForm2.add(bomType)"
				icon="plus">新增</a-button>
			<a-button type="danger" v-if="isProductionDepartment() || managerOrFinance()"
				@click="$refs.replaceForm.add(bomType)" icon="tool">物料替换</a-button>

			<Export text="导出" v-if="bomType == 1 && hasBtnPremission(['emsBom:export'])" title="基础bom" url="/emsBom/export"
			:isBody="true"
				:obj="{
					bomName: queryParam.bomName,
					bomClass: queryParam.bomClass,
					materialCode: queryParam.materialCode,
					isDisable: queryParam.isDisable
				}" />
			<Export text="导出" v-if="bomType == 2 && hasBtnPremission(['emsBom:makeUpExport'])" title="组合bom"
				:isBody="true"
				url="/emsBom/makeUpExport" :obj="{
					bomName: queryParam.bomName,
					bomClass: queryParam.bomClass,
					materialCode: queryParam.materialCode,
					isDisable: queryParam.isDisable
				}" />
			<!-- <a-button type="danger" v-if="bomType == 1 && hasBtnPremission(['emsBom:export'])" icon="tool">导出</a-button>
			<a-button type="danger" v-if="bomType == 2 && hasBtnPremission(['emsBom:makeUpExport'])" icon="tool">导出</a-button> -->
		</div>

		<s-table ref="table" size="default" :columns="myColumn" :data="loadData" :alert="true"
			:rowKey="(record) => record.code" :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">

			<span slot="action" slot-scope="text, record">
				<a @click="$refs.editForm2.readonly(record)">详情</a>
				<a-divider type="vertical" v-if="hasBtnPremission(['emsBom:edit'])" />
				<a @click="$refs.editForm2.edit(record)" v-if="hasBtnPremission(['emsBom:edit'])">编辑</a>
				<template v-if="bomType == 1">
					<a-divider type="vertical" v-if="hasBtnPremission(['emsMaterial:referenceStatistics'])" />
					<a @click="$refs.usageChart.show({ ...record, typeId: 2 })"
						v-if="hasBtnPremission(['emsMaterial:referenceStatistics'])">引用情况</a>
				</template>

				<!--        <a-dropdown>-->
				<!--          <a class="ant-dropdown-link"> 更多 <a-icon type="down"/></a>-->
				<!--          <a-menu slot="overlay">-->
				<!--            <a-menu-item>-->
				<!--              <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => del(record)">-->
				<!--                <a>删除</a>-->
				<!--              </a-popconfirm>-->
				<!--            </a-menu-item>-->
				<!--          </a-menu>-->
				<!--        </a-dropdown>-->
			</span>
			<span slot="isDisable" slot-scope="text,record">
				<a-tag v-if="text == 1" color="#52C41A">正常</a-tag>
				<a-tag v-if="text == 2" color="#F52251">停用</a-tag>
			</span>
			<!-- <span slot="image" slot-scope="text">
				<image-preview :images="text" />
			</span> -->
			<span slot="image" slot-scope="text,record">
				<image-preview1 :images="text" :imageUrl="record.imageUrl" />
			</span>
		</s-table>

		<add-form2 ref="addForm2" @ok="handleOk" />
		<edit-form2 ref="editForm2" @ok="handleOk" />
		<replace-form ref="replaceForm" />
		<usage-chart ref="usageChart" />

		<ems-material-to-pool-form1 ref="emsMaterialToPoolForm1" />
	</a-card>
</template>

<script>
import { STable } from '@/components'
import { page, del, detailFull } from '@/api/modular/main/emsbom/emsBomManage'
import addForm from './emsBomAddForm'
import addForm1 from './emsBomAddForm1'
import addForm2 from './emsBomAddForm2'

import replaceForm from './emsBomReplaceForm.vue'

import editForm from './emsBomEditForm'
import editForm2 from './emsBomEditForm2'
import { sysDictTypeDropDown } from '@/api/modular/system/configManage'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getUrlParam } from '@/utils/util'
import EmsMaterialToPoolForm1 from '@/views/main/emsmaterial/emsMaterialToPoolForm1'
import UsageChart from '@/views/main/materialManagement/materialBaseTable/usageChart'
import { hasBtnPermission } from '@/utils/permissions'

export default {
	components: {
		STable,
		addForm,
		addForm1,
		addForm2,
		replaceForm,
		editForm,
		editForm2,
		EmsMaterialToPoolForm1,
		UsageChart
	},
	mounted() {
		// 从字典表获取分类数据
		this.axios.get('/sysDictData/list?typeCode=ems_bom_class').then((res) => {
			console.log('字典表数据', res)
			this.typeList = res.data
		})
	},
	data() {
		return {
			typeList: [], //从字典表获取的分类数据
			advanced: false, // 高级搜索 展开/关闭
			queryParam: {
				isDisable: null,
			},  // 查询参数
			columns: [       // 表头
				{
					title: '序号', width: '80px',
					align: 'center',
					customRender: (text, record, index) => `${index + 1}`,
				},
				{
					title: 'BOM名称',
					dataIndex: 'bomName',
					ellipsis: true
				},
				{
					title: 'BOM编码',
					dataIndex: 'bomCode',
					ellipsis: true
				},
				{
					title: '图片',
					dataIndex: 'image',
					// customRender: (text, record, index) => this.$util.createFcImage(this.$createElement, text)
					scopedSlots: { customRender: 'image' }
				},
				{
					title: '更新时间',
					dataIndex: 'createTime',
				},
				{
					title: '分类',
					dataIndex: 'bomClassName'
				},
				{
					title: '成本',
					dataIndex: 'cost'
				},
				{
					title: '状态',
					dataIndex: 'isDisable',
					scopedSlots: { customRender: 'isDisable' }
					// customRender: (text, record, index) => record.isDisable == 1 ? '正常' : '停用',
				},
				{
					title: '操作',
					dataIndex: 'action',
					width: '200px',
					scopedSlots: { customRender: 'action' }
				}
			],
			// 加载数据方法 必须为 Promise 对象
			loadData: parameter => {
				this.queryParam.bomType = this.bomType
				return page(Object.assign(parameter, this.queryParam)).then((res) => {
					return res.data
				})
			},
			selectedRowKeys: [],
			selectedRows: [],
			defaultExpandedKeys: [],
			replaceFields: {
				key: 'id',
			},
			toPoolLoading: false
		}
	},
	computed: {
		routePath() {
			let urlParam = getUrlParam(this.$route.path)
			return urlParam
		},
		bomType() {
			return this.routePath.bomType
		},
		myColumn() {
			let result = this.columns
			if (!this.managerOrFinance()) {
				result = result.filter(item => item.dataIndex !== 'cost')
			}
			return result
		}
	},
	watch: {
		bomType() {
			this.queryParam.bomType = this.bomType
			this.handleOk()
		}
	},
	created() {

	},
	methods: {
		del(record) {
			del(record).then((res) => {
				if (res.success) {
					this.$message.success('删除成功')
					this.$refs.table.refresh()
				} else {
					this.$message.error('删除失败：' + res.message)
				}
			}).catch((err) => {
				this.$message.error('删除错误：' + err.message)
			})
		},
		toggleAdvanced() {
			this.advanced = !this.advanced
		},
		handleOk() {
			this.$refs.table.refresh()
		},
		onSelectChange(selectedRowKeys, selectedRows) {
			this.selectedRowKeys = selectedRowKeys
			this.selectedRows = selectedRows
		},
		imageURLFormat(text) {
			let token = Vue.ls.get(ACCESS_TOKEN)
			return `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${text}&token=${token}`
		},
		preview(url) {
			this.previewVisible = true
			this.previewImage = url
		},
		getSelectRows() {
			return this.selectedRows
		},
		bomToPool() {
			console.log(12312);

			if (this.selectedRows.length == 0) {
				this.$message.error('请选择一个BOM')
				return
			} else if (this.selectedRows.length > 1) {
				this.$message.error('只能选择一个BOM')
				return
			} else {


				// 查BOM中所有的物料
				let bomId = this.selectedRows[0].bomId
				console.log(bomId);
				this.toPoolLoading = true
				detailFull({ bomId }).then(res => {
					this.toPoolLoading = false
					let bomMaterials = []
					let data = res.data
					bomMaterials = bomMaterials.concat(data.bomMaterials)
					for (const otherBom of data.otherBoms) {
						bomMaterials = bomMaterials.concat(otherBom.bomMaterials)
					}
					// 遍历集合,将相同的物料进行数量累加
					let poolType = this.$businessEnum.ORDER_TYPE_ENUM.purchaseOrder.id
					let newArray = []
					for (const material of bomMaterials) {
						console.log("material---------", material);

						let findItem = newArray.find(item => item.materialId == material.materialId)
						if (!findItem) {
							newArray.push({
								materialId: material.materialId,
								materialCode: material.materialCode,
								materialName: material.materialName,
								remark: material.remark,
								number: material.materialNumber,
								poolType,
								image: material.image,
								imageUrl: material.imageUrl,
								materialType: material.materialType
							})
						} else {
							findItem.number += material.materialNumber
						}
					}

					// 添加到采购池编辑页中
					let rows = newArray.map(row => Object.assign(row, { poolType }))
					this.$refs.emsMaterialToPoolForm1.add1(rows)
				})
			}
		}
	}
}
</script>

<style lang="less">
.table-operator {
	margin-bottom: 18px;
}

button {
	margin-right: 8px;
}

.table-image {
	cursor: pointer;
	max-width: 100px;
	max-height: 50px;
	border: solid 1px #cccccc;
}
</style>
